using UnityEngine;
using WebSocketSharp;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Text;
using System;
using PimDeWitte.UnityMainThreadDispatcher;

public class GameController : MonoBehaviour
{
    public Transform[] team1Cubes;
    public Transform[] team2Cubes;
    public float spawnRadius = 5.0f;
    public GameObject[] enemyPrefabs;
    public Dictionary<string, GameObject> enemies = new Dictionary<string, GameObject>();
    public WebSocket webSocket;
    public float moveSpeed = 5.0f;

    private void Start()
    {
        webSocket = new WebSocket("ws://192.168.43.1:8083/websocket");
        webSocket.OnMessage += OnWebSocketMessage;
        webSocket.Connect();
        Debug.Log("WebSocket connected to ws://192.168.43.1:8083/websocket");

        if (enemyPrefabs != null && enemyPrefabs.Length > 0 && team1Cubes.Length > 0 && team2Cubes.Length > 0)
        {
            // Do additional initialization if needed
        }
        else
        {
            Debug.LogError("Check references in the Inspector.");
        }
    }

    void Update()
    {
        foreach (var enemy in enemies.Values)
        {
            MoveEnemy(enemy);
        }
    }

    private void OnWebSocketMessage(object sender, MessageEventArgs e)
    {
        string message = e.Data;
        string utf8Message = Encoding.UTF8.GetString(Encoding.Default.GetBytes(message));
        try
        {
            JObject jsonData = JObject.Parse(utf8Message);
            HandleUserAction(jsonData);
        }
        catch (JsonReaderException ex)
        {
            Debug.LogError("Error parsing JSON: " + ex.Message);
        }
        if (!webSocket.IsAlive)
        {
            Debug.LogWarning("WebSocket connection closed, reconnecting...");
            webSocket.Connect();
            Debug.Log("WebSocket reco ws://192.168.43.1:8083/websocket");
        }
    }

    private void HandleUserAction(JObject jsonData)
    {
        UnityMainThreadDispatcher.Instance().Enqueue(() =>
        {
            try
            {
                if (jsonData["nickName"] != null && jsonData["content"] != null)
                {
                    string username = jsonData["nickName"].ToString();
                    int content;

                    if (int.TryParse(jsonData["content"].ToString(), out content))
                    {
                        GenerateEnemy(username, content);
                    }
                    else
                    {
                        Debug.LogError("无效的用户数据: " + jsonData.ToString());
                    }
                }
                else
                {
                    Debug.LogError("无效的用户数据在消息中.");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("HandleUserAction 错误: " + ex.Message);
                // 记录整个异常以获取更详细的信息
                Debug.LogException(ex);
            }
        });
    }

    private void GenerateEnemy(string username, int content)
    {
        int prefabIndex;
        Transform selectedCube;

        if (content == 1)
        {
            prefabIndex = UnityEngine.Random.Range(0, 4); // 随机选择0-3得预制体
            selectedCube = GetRandomCube(team1Cubes);
        }
        else if (content == 2)
        {
            prefabIndex = UnityEngine.Random.Range(4, 8); // 随机选择4-7得预制体
            selectedCube = GetRandomCube(team2Cubes);
        }
        else
        {
            Debug.LogError("无效的内容: " + content);
            return;
        }

        GameObject selectedPrefab = enemyPrefabs[prefabIndex];
        Vector3 spawnPosition = GetRandomSpawnPosition(selectedCube.position);

        // 计算朝向相反的旋转方向
        Quaternion rotation = (content == 1) ? selectedCube.rotation : Quaternion.LookRotation(-selectedCube.forward);

        GameObject newEnemy = Instantiate(selectedPrefab, spawnPosition, rotation);
        Rigidbody enemyRigidbody = newEnemy.AddComponent<Rigidbody>();
        enemyRigidbody.freezeRotation = true;

        newEnemy.name = $"{selectedPrefab.name}_{username}";
        enemies.Add(username, newEnemy);

        Debug.Log($"敌人生成在阵营 {content} 的 cube 位置: {spawnPosition}, 玩家名字: {username}");
    }

    private Transform GetRandomCube(Transform[] cubes)
    {
        return cubes[UnityEngine.Random.Range(0, cubes.Length)];
    }

    private void MoveEnemy(GameObject enemy)
    {
        if (enemy == null)
        {
            return;
        }

        enemy.transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
    }

    public void RemoveEnemyFromList(string username)
    {
        if (enemies.ContainsKey(username))
        {
            GameObject enemyToRemove = enemies[username];
            enemies.Remove(username);
            Destroy(enemyToRemove);
        }
    }

    private void OnDestroy()
    {
        if (webSocket != null && webSocket.IsAlive)
        {
            webSocket.Close();
        }
    }

    private Vector3 GetRandomSpawnPosition(Vector3 basePosition)
    {
        Vector2 randomOffset = UnityEngine.Random.insideUnitCircle.normalized * spawnRadius;
        return basePosition + new Vector3(randomOffset.x, 0.0f, randomOffset.y);
    }
}
